package com.lbj.mall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lbj.mall.common.constant.WarePurchaseNeed;
import com.lbj.mall.common.utils.PageUtils;
import com.lbj.mall.common.utils.Query;
import com.lbj.mall.ware.dao.PurchaseDetailDao;
import com.lbj.mall.ware.entity.PurchaseDetailEntity;
import com.lbj.mall.ware.entity.vo.DoneItem;
import com.lbj.mall.ware.service.PurchaseDetailService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("purchaseDetailService")
public class PurchaseDetailServiceImpl extends ServiceImpl<PurchaseDetailDao, PurchaseDetailEntity> implements PurchaseDetailService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<PurchaseDetailEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(item -> {
                item.eq("id", key).or().eq("sku_id", key);
            });
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("status", status);
        }
        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)) {
            wrapper.eq("ware_id", wareId);
        }

        IPage<PurchaseDetailEntity> page = this.page(
                new Query<PurchaseDetailEntity>().getPage(params), wrapper);

        return new PageUtils(page);
    }

    /**
     * 根据采购单id获取所有的采购信息
     */
    @Override
    public List<PurchaseDetailEntity> listByPurchaseIds(List<Long> ids) {
        return list(new QueryWrapper<PurchaseDetailEntity>()
                .in("purchase_id", ids)
                .and(item -> {
                    item.eq("status", WarePurchaseNeed.NEW.getCode())
                            .or().eq("status", WarePurchaseNeed.SELECT.getCode());
                }));
    }

    @Override
    public void updateBatch(List<DoneItem> items) {
        List<PurchaseDetailEntity> collectList = items.stream().map(item -> {
            PurchaseDetailEntity entity = new PurchaseDetailEntity();
            entity.setId(item.getItemId());
            entity.setStatus(item.getStatus());
            return entity;
        }).collect(Collectors.toList());
        updateBatchById(collectList);
    }
}